using System.Collections.Generic;
using System.Linq;
using Rubikev.Common;
using Rubikev.Common.DependencyInjection;
using StructureMap;

namespace Rubikev.StructureMap
{
   /// <summary>
   /// Initializes the StructureMap dependencies when the application starts
   /// </summary>
   public class ApplicationConfiguration : IApplicationLifetimeAware
   {
      /// <summary>
      /// Initializes the StructureMap object factory
      /// </summary>
      public void OnStarting()
      {
         // Initialize using the StructureMap types, then adding any other IRegisters that need to be injected
         ObjectFactory.Initialize(x =>
                                     {
                                        x.AddRegistry<StuctureMapRegister>();
                                        x.AddRegistry<ScanCurrentDirectoryRegister>();
                                     });
         
         // Iterate over any IRegisters that were found, and add them to the container as well
         // This is so that any of them that depend on the StructureMap type providers at construction time now have access to them
         IEnumerable<IRegister> registries = ObjectFactory.GetAllInstances<IRegister>();//.Select(r => new RegisterAdapter(r));
         ObjectFactory.Configure(x =>
                                    {
                                       foreach (IRegister registry in registries)
                                       {
                                          x.AddRegistry(new RegisterAdapter(registry));
                                       }
                                    });
      }

      /// <summary>
      /// Does nothing
      /// </summary>
      public void OnStarted()
      {
      }

      /// <summary>
      /// Does nothing
      /// </summary>
      public void OnExiting()
      {
      }

      /// <summary>
      /// Does nothing
      /// </summary>
      public void OnExited()
      {
      }
   }
}